/** * 公共组件->图片上传 */
<template>
  <div>
    <div class="upload-list" v-for="(item, index) in fileList" :key="index">
      <img :src="imgBase + item.resUrl" alt=""/>
      <div class="upload-list-cover">
        <Icon type="ios-eye" @click.native="handlePictureCardPreview(item)"></Icon>
        <Icon type="ios-trash" @click.native="handleRemove(index)"></Icon>
      </div>
    </div>
    <Upload
      ref="upload"
      :format="fileType"
      :accept="fileType.map(v => {return '.' + v}).join(',')"
      :show-upload-list="false"
      :on-success="handleUploadSuccess"
      :headers="headers"
      :on-format-error="handleUploadError"
      :on-exceeded-size="handleExceed"
      :before-upload="handleBeforeUpload"
      :multiple="limit > 1 ? true : false"
      type="drag"
      :disabled="disabled"
      :action="uploadImgUrl"
      :class="{hide: this.fileList.length >= this.limit}"
    >
      <Icon type="md-add" size="28" color="#8c939d"></Icon>
    </Upload>

    <!-- 上传提示 -->
    <div class="upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
      的文件
    </div>

    <Modal class="imgss" title="预览" v-model="modalVisible">
      <img :src="imgBase + modalImgUrl" alt=""/>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
import {base} from "@/libs/axios";

export default {
  name: "imageUpload",
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 2,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      modalImgUrl: "",
      modalVisible: false,
      imgBase: this.$config.fileUrl(),
      uploadImgUrl: base + this.$config.uploadUrl, // 上传的图片服务器地址
      headers: {
        token: JSON.parse(window.localStorage.getItem("myData")).token,
      },
      fileList: []
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = {id: item, resUrl: item};
            }
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 删除图片
    handleRemove(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.fileList);
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      if (res.code == 20000) {
        this.fileList.push({id: res.data.id, resUrl: res.data.resUrl});
        this.$emit("input", this.fileList);
      } else {
        this.$Message.error(res.message);
      }
    },
    // 上传前
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$Notice.warning({
          title: '文件格式不正确',
          desc: `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
        })
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$Notice.warning({
            title: "上传失败",
            desc: `上传图片大小不能超过 ${this.fileSize} MB!`,
          });
          return false;
        }
      }
    },
    // 文件个数超出
    handleExceed() {
      this.$Notice.warning({
        title: `上传文件数量不能超过 ${this.limit} 个!`,
      })
    },
    // 上传失败
    handleUploadError(res) {
      this.$Notice.error({
        title: "上传失败, 请重试",
      });
    },
    // 预览
    handlePictureCardPreview(file) {
      this.modalImgUrl = file.resUrl;
      this.modalVisible = true;
    },
  }
};
</script>
<style scoped lang="less">
/deep/ .ivu-upload {
  display: inline-block;
}

/deep/ .ivu-upload.ivu-upload-drag {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  width: 148px;
  height: 148px;
  line-height: 146px;
  border-radius: 4px;
}

// .ivu-upload 控制加号部分
/deep/ .hide.ivu-upload {
  display: none;
}

.upload__tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}

.upload-list {
  display: inline-block;
  width: 148px;
  height: 148px;
  text-align: center;
  line-height: 148px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 8px;
}

.upload-list img {
  width: 100%;
  height: 100%;
}

.upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, .5);
}

.upload-list:hover .upload-list-cover {
  display: block;
}

.upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin-left: 15px;
}

.upload-list-cover i:first-child {
  margin-left: 0;
}
</style>
